package com.wiz.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.web.manager.ServiceManager;

public class MainHandler extends ChannelInitializer<SocketChannel> {
	
	private ServiceManager serviceManager;
	private NettyXmlParseFactory wizXmlFactory;
	
	public MainHandler(ServiceManager serviceManager,NettyXmlParseFactory wizXmlFactory){
		super();
		this.serviceManager = serviceManager;
		this.wizXmlFactory = wizXmlFactory;
	}

	@Override
	protected void initChannel(SocketChannel arg0) throws Exception {
//		//读超时 20S无数据超时
//		arg0.pipeline().addLast(new ReadTimeoutHandler(20, TimeUnit.SECONDS));
//		//写超时 30S无数据超时
//		arg0.pipeline().addLast(new WriteTimeoutHandler(24, TimeUnit.SECONDS));
		//client异常中断
//		arg0.pipeline().addLast("closehandler",new CloseHandler(serviceManager));
		//半包解码
		arg0.pipeline().addLast("frameDecoder",new ProtobufVarint32FrameDecoder());
		//解码还原类型
		arg0.pipeline().addLast("protobufDecoder",new ProtobufDecoder(NettyMessageTO.MessageContent.getDefaultInstance()));
		//半包加码
		arg0.pipeline().addLast("frameEncoder",new ProtobufVarint32LengthFieldPrepender());
		//加码处理
		arg0.pipeline().addLast("protobufEncoder",new ProtobufEncoder());
		//心跳设置（读，写，全）
		arg0.pipeline().addLast(new IdleStateHandler(90, 120, -1));
		//心跳逻辑器
		arg0.pipeline().addLast("idelhandler",new IdleHandler(serviceManager));
		//登录逻辑器
		arg0.pipeline().addLast("loginhandler",new LoginHandler(serviceManager,wizXmlFactory));
		//业务处理handler
		arg0.pipeline().addLast("bussinesshandler",new BussinessHandler(serviceManager,wizXmlFactory));
	}

}
